﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.AuthApiServiceReference;
using Web.Framework;
using Web.Framework.Config;
using System.Configuration;
using WebAppAuthAdmin.Code;
using System.Text;

namespace WebAppAuthAdmin.Account
{
    public partial class Login : System.Web.UI.Page
    {       
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SiteMaster masterPage = (SiteMaster)this.Master;
                masterPage.MakeMenuVisible(false);
                masterPage.SetContextPicker(string.Empty); // Sino trae problemas de permisos
                LoginUser.Authenticate += new AuthenticateEventHandler(LoginUser_Authenticate);

                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                RegisterCompaniesIntoJS();

                BaseWebPage.ApplicationId = configuration.ApplicationId;                            
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void RegisterCompaniesIntoJS()
        {
            //// Tengo que registrar el array en javascript
            //StringBuilder builder = new StringBuilder();
            //string separador = string.Empty;
            //builder.Append("<script type='text/javascript' >");
            //builder.Append("var companies = [];");
            //foreach (CompanyConfiguration companyConfiguration in BasePage.GetCompanyConfigurationList(this.Page))
            //{
            //    builder.AppendFormat("companies[{0}] = '{1}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath);
            //}

            //builder.Append("</script>");
            //Page.ClientScript.RegisterStartupScript(typeof(string), "companias", builder.ToString());
        }

        private void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            try
            {                                                
                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                if (LoginUser.UserName == configuration.SuperAdminName && LoginUser.Password == configuration.SuperAdminPassword)
                {
                    e.Authenticated = true;
                    BaseWebPage.CompanyId = 0;
                    BaseWebPage.IsAdmin = true;
                }
                else if (e.Authenticated = WebServiceHelper.Authenticate(BaseWebPage.ApplicationId, 0, LoginUser.UserName, LoginUser.Password))
                {
                    BaseWebPage.CompanyId = 0;
                    BaseWebPage.IsAdmin = false;
                }

                if (e.Authenticated)
                {
                    // seteo el nombre del usuario en el login
                    string displayName = LoginUser.UserName;
                    var adUser =  WebServiceHelper.GetUsers(BaseWebPage.ApplicationId, BaseWebPage.CompanyId, LoginUser.UserName).SingleOrDefault();
                    if (adUser != null)
                    {
                        if (!String.IsNullOrEmpty(adUser.GivenName))
                        {
                            displayName = adUser.GivenName;
                        }
                    }

                    BaseWebPage.DisplayUserName = displayName;                    
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        void LoginUser_LoggedIn(object sender, EventArgs e)
        {
            //TODO: cargar información de operaciones permitidas para el usuario
            //var a = this.User.Identity;
        }

        void LoginUser_LoggingIn(object sender, LoginCancelEventArgs e)
        {
            // e.Cancel = true;            
        }
    }
}
